package com.szh.mysobproject.ui.activity.msg

import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import by.kirich1409.viewbindingdelegate.viewBinding
import com.dylanc.longan.lifecycleOwner
import com.szh.mysobproject.R
import com.szh.mysobproject.action.OnBack2TopListener
import com.szh.mysobproject.action.StatusAction
import com.szh.mysobproject.app.AppActivity
import com.szh.mysobproject.databinding.QaMsgListActivityBinding
import com.szh.mysobproject.ui.activity.BrowserActivity
import com.szh.mysobproject.ui.adapter.AdapterDelegate
import com.szh.mysobproject.ui.adapter.QaMsgAdapter
import com.szh.mysobproject.util.*
import com.szh.mysobproject.viewmodel.MsgViewModel
import com.szh.mysobproject.widget.StatusLayout
import kotlinx.coroutines.flow.collectLatest

/**
 * @author : create by  szh
 * @date : 2022/7/12 15:28
 * @desc :问答消息列表
 */

class QaMsgListActivity : AppActivity(), StatusAction, OnBack2TopListener {

    private val mBinding by viewBinding<QaMsgListActivityBinding>()
    private val mMsgViewModel by viewModels<MsgViewModel>()
    private val mAdapterDelegate = AdapterDelegate()
    private val mQaMsgAdapter = QaMsgAdapter(mAdapterDelegate)
    private val loadStateListener = loadStateListener(mQaMsgAdapter) {
        mBinding.refreshLayout.finishRefresh()
    }


    override fun getLayoutId(): Int = R.layout.qa_msg_list_activity

    override fun initView() {
        mBinding.rvQaMsgList.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mQaMsgAdapter
            addItemDecoration(SimpleLinearSpaceItemDecoration(1.dp))
        }
    }

    override fun initData() {
        lifecycleOwner.lifecycleScope.launchWhenCreated {
            mMsgViewModel.getQaMsgList().collectLatest {
                mQaMsgAdapter.submitData(it)
            }
        }
    }

    override fun initEvent() {
        titleBar?.setDoubleClickListener {
            onBack2Top()
        }
        mBinding.refreshLayout.setOnRefreshListener {
            mQaMsgAdapter.refresh()
        }
        mQaMsgAdapter.addLoadStateListener(loadStateListener)
        mAdapterDelegate.setOnItemClickListener { _, position ->
            val item = mQaMsgAdapter.snapshot()[position] ?: return@setOnItemClickListener
            mMsgViewModel.readQaMsg(item.id).observe(this) {}
            val url = "$SUNNY_BEACH_QA_URL_PRE${item.wendaId}"
            BrowserActivity.start(this, url)
        }
    }

    override fun onBack2Top() {
        mBinding.rvQaMsgList.smoothScrollToPosition(0)
    }

    override fun getStatusLayout(): StatusLayout = mBinding.hlQaMsgHint

    override fun onDestroy() {
        super.onDestroy()
        mQaMsgAdapter.removeLoadStateListener(loadStateListener)
    }
}